/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller.SRV;

import com.google.gson.Gson;
import entity.MDoctor;
import entity.MMapHospitalDoctor;
import entity.SrvCureservice;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//import org.json.simple.JSONValue;
import session.MDoctorFacade;
import session.SrvCureserviceFacade;
import session.MMapHospitalDoctorFacade;

/**
 *
 * @author SUNTIPARB
 */
@WebServlet(name="SRV_CureServiceDetail",
loadOnStartup = 1,
urlPatterns={"/SRV/CureServiceDetail",
                "/SRV/CureServiceDetail/getDoctor",
                "/SRV/CureServiceDetail/formCureService_Submit"})
public class SRV_CureServiceDetail extends HttpServlet {
   
    @EJB
    private SrvCureserviceFacade srvCureserviceFacade;
    @EJB
    private MDoctorFacade mDoctorFacade;
    @EJB
    private MMapHospitalDoctorFacade mMapHospitalDoctorFacade;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        // if category page is requested
        if (userPath.equals("/SRV/CureServiceDetail")) {
            response.setContentType("text/html;charset=utf-8");
            ResourceBundle resource = ResourceBundle.getBundle("Constant_en");
            String cureServiceId = request.getParameter("id");
            if (!cureServiceId.equals("-1")){
                List<SrvCureservice> lSrvCureservice;
                try {
                    //Query Java Object
                    lSrvCureservice = srvCureserviceFacade.findByServiceId(cureServiceId);
                    if (!lSrvCureservice.isEmpty()) {
                        request.setAttribute("cureServiceId", cureServiceId);
                        for (SrvCureservice obj : lSrvCureservice) {
                            request.setAttribute("txtName", obj.getName());
                            request.setAttribute("txtPrice", obj.getPrice().toString());
                            request.setAttribute("txtCurrency", obj.getCurrency());
                            if (obj.getMDoctor() != null) {
                                request.setAttribute("ddlDoctorId", obj.getMDoctor().getId());
                                request.setAttribute("ddlDoctorName", obj.getMDoctor().getName()+" "+obj.getMDoctor().getSurname());
                            }else{
                                request.setAttribute("ddlDoctorId", "");
                                request.setAttribute("ddlDoctorName", resource.getString("project.select.default"));
                            }
                        }
                    }
                } catch (Exception ex) {
                    System.out.println("Error message" + ex.getMessage());
                } finally {
                    lSrvCureservice = null;
                }
            }else{
                request.setAttribute("cureServiceId", cureServiceId);
                request.setAttribute("txtName", "");
                request.setAttribute("txtPrice", "");
                request.setAttribute("txtCurrency", "");
                request.setAttribute("ddlDoctorId", "");
                request.setAttribute("ddlDoctorName", resource.getString("project.select.default"));
            }

            userPath = "/SRV/CureServiceDetail";
        }
        
        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as
        // 8-bit Unicode (e.g., for Czech characters)
        Boolean isDispatcher = true; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();


        if (userPath.equals("/SRV/CureServiceDetail/formCureService_Submit")) {

            String cureServiceId = (request.getParameter("cureServiceId") != null) ? request.getParameter("cureServiceId") : "-1";
            String txtName = (request.getParameter("txtName") != null) ? request.getParameter("txtName") : "";
            String txtPrice = (request.getParameter("txtPrice") != null) ? request.getParameter("txtPrice") : "";
            String txtCurrency = (request.getParameter("txtCurrency") != null) ? request.getParameter("txtCurrency") : "";
            String ddlDoctorId = (request.getParameter("ddlDoctorName") != null) ? request.getParameter("ddlDoctorName") : "";
            String ddlHospitalId = "1"; // fix for prototype

            List<MMapHospitalDoctor> lMMapHospitalDoctor;
            try {
                //Query Java Object
                lMMapHospitalDoctor = mMapHospitalDoctorFacade.findByDoctorId(ddlDoctorId);

                if (!lMMapHospitalDoctor.isEmpty()) {
                    for (MMapHospitalDoctor obj : lMMapHospitalDoctor) {
                        if (obj.getMDoctor() != null) {
                            ddlHospitalId = obj.getMHospital().getId().toString();
                        }
                    }
                }

            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            }

            PrintWriter out = response.getWriter();
            try {
                //Query Java Object

                if (!cureServiceId.equals("-1")){
                    srvCureserviceFacade.EditService(cureServiceId, txtName, txtPrice, txtCurrency, ddlDoctorId, ddlHospitalId);
                }else{
                    srvCureserviceFacade.AddService(txtName, txtPrice, txtCurrency, ddlDoctorId, ddlHospitalId);
                }
                
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
            }

            isDispatcher = false;
        }

        if (userPath.equals("/SRV/CureServiceDetail/getDoctor")) {
            response.setContentType("text/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            List<MDoctor> lMDoctor;
            Map mapDoctor = null;
            List listDoctor = new LinkedList();
            String strJson = "";

            try {
                //Query Java Object
                Gson gson = new Gson();
                lMDoctor = mDoctorFacade.LoadDataDoctor("", "", "", "id", "asc");
                if (!lMDoctor.isEmpty()) {
                    for (MDoctor obj : lMDoctor) {
                        mapDoctor = new LinkedHashMap();
                        mapDoctor.put("name",obj.getName() + " " + obj.getSurname());
                        mapDoctor.put("value",obj.getId());
                        listDoctor.add(mapDoctor);
                    }
                }

                //@TODO : Add Json Value
                strJson = gson.toJson(listDoctor);//JSONValue.toJSONString(listDoctor);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lMDoctor = null;
                strJson = null;
            }
            isDispatcher = false;
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

    }
}
